<?php

	class Model_Auth
	{
		private static $instance;

		public static function getInstance()
		{
			if (!self::$instance) {
				self::$instance = new Model_Auth();
			}

			return self::$instance;
		}

		public function getAuthUser($login, $password)
		{
			$db = Database::getInstance();
			if (empty($login) || empty($password)) return false;

			$login_esc    = $db->escape($login);
			$password_esc = $db->escape($password);

			if ($user = AppCache::getInstance()->get('User:' . $login)) {
				/* @var $result OUser */
				if ($user->password !== $password) return false;

				$user->last_login = date('Y-m-d H:i:s');

				return $user;
			}

			$user = $db->fetch_object($db->query("SELECT * FROM `user` WHERE `login`='{$login_esc}' AND `password`='{$password_esc}' LIMIT 1"), 'OUser');
			if (empty($user)) return false;
			/* @var $user OUser */

			$user->last_login = date('Y-m-d H:i:s');
			$this->setUser($user);

			AppCache::getInstance()->set('User:' . $user->login, $user);

			return $user;
		}

		public function getUsers()
		{
			$db = Database::getInstance();

			$result    = array();
			$for_cache = array();

			$q = $db->query("SELECT * FROM `user`");
			while ($user = $db->fetch_object($q, 'OUser')) {
				/* @var $user OUser */
				$for_cache['User:' . $user->login] = $user;
				$result[]                          = $user;
			}

			AppCache::getInstance()->sets($for_cache);

			return $result;
		}

		/**
		 * @param $login
		 * @return bool|OUser
		 */
		public function getUser($login)
		{
			$db    = Database::getInstance();
			$login = $db->escape($login);

			$user = $db->fetch_object($db->query("SELECT * FROM `user` WHERE `login`='{$login}'"), 'OUser');
			if (empty($user)) return false;
			/* @var $user OUser */

			AppCache::getInstance()->set('User:' . $user->login, $user);

			return $user;
		}

		public function delUser($login)
		{
			$db = Database::getInstance();

			$login = $db->escape($login);
			$db->query("DELETE FROM `user` WHERE `login`='{$login}'");

			AppCache::getInstance()->del('User:' . $login);
		}

		public function setUser(OUser $user)
		{
			$db = Database::getInstance();

			$result = $db->insertUpdateTable('user', 'login', $user);

			AppCache::getInstance()->del('User:' . $user->login);

			return $result;
		}

		public function getAllPermissions()
		{
			$db = Database::getInstance();

			return $db->fetch_query('SELECT * FROM `user_permis` ORDER BY `title`');
		}

	}